package com.jkgj.skykingkong.tms.domain.model.rbac;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.ebean.domain.AbstractAuditableEntity;
import org.springframework.data.ebean.domain.AggregateRoot;

/**
 * @author Xuegui Yuan
 */
@Getter
@Setter
@AllArgsConstructor
@Entity
@Table(name = "sys_role")
@AggregateRoot
public class Role extends AbstractAuditableEntity {
  /**
   * 代码
   */
  private String code;
  /**
   * 名称
   */
  private String name;

  /**
   * 权限列表
   */
  @ManyToMany(fetch = FetchType.EAGER)
  @JoinTable(name = "sys_role_permission", joinColumns = {@JoinColumn(name = "role_id")}, inverseJoinColumns = {
      @JoinColumn(name = "permission_id")})
  private List<Permission> permissions;

  /**
   * 获取拥有的所有权限代码
   */
  public Set<String> getPermissionCodes() {
    return getPermissions().stream().map(p -> p.getCode()).collect(Collectors.toSet());
  }

  /**
   * 分配权限
   *
   * @param permissions
   */
  public void grantPermissions(List<Permission> permissions) {
    this.getPermissions().clear();
    this.getPermissions().addAll(permissions);
  }
}
